const db = require("../db")
const { querySql , queryOne }=require("../db")

async function getAdminArticleList(data){//获取帖子列表
    const {
        category_id,//分类
        uid,//发布人id
        title,//文章
        state,//状态
        isTop,//置顶
        sort,//排序
        page = 1,
        limit = 20
    } = data


    const offset = (page - 1) * limit;
    let bookSql = `select a.*,u.nickname,r.msg from fs_article a left join fs_user u  on a.uid = u.id left join fs_reject r  on a.id = r.aid `
    let where = 'where'
    category_id && (where = db.and(where,'category_id',category_id))
    state && (where = db.and(where,'state',state))
    uid && (where = db.and(where,'uid',uid))
    title && (where = db.andLikeTile(where,'title',title))
    if (where !== 'where') {
        bookSql = `${bookSql} ${where}`
    }
    if (sort) {
        const symbol = sort[0]
        const column = sort.slice(1, sort.length)
        const order = symbol === '+' ? 'asc' : 'desc'
        bookSql = `${bookSql} order by ${column} ${order}`
    }
    
    let countSql = `select count(*) as count from fs_article`
    if (where !== 'where') {
        countSql = `${countSql} ${where}`
    }
    bookSql = `${bookSql} limit ${ limit } offset ${offset}`
    // list = await db.querySql(bookSql)
    const list = await db.querySql(bookSql)

    const count = await db.querySql(countSql)
    return { list, count: count[0].count, page, limit }    
}


function getArticle(data){//查询帖子详情
    return queryOne(`select a.*,u.nickname,u.avatar from fs_article as a join fs_user as u on a.uid = u.id where a.id='${data.id}'`)
}

function updataArticle(data){//修改帖子
    return  new Promise( async (resolve,reject)=>{
        try{
            await db.update(data,'fs_article',`where id='${data.id}'`)
           
            resolve()
            
         }catch(e){
             reject()
         }
    
   })
}


function addReject(data){//添加驳回原因
    return  new Promise( async (resolve,reject)=>{
        try{
            await db.insert(data,'fs_reject')
            resolve()
         }catch(e){
             reject()
         }
    
   })
}


function updataReject(data){//修改驳回原因
    return  new Promise( async (resolve,reject)=>{
        try{
            await db.update(data,'fs_reject',`where aid='${data.aid}'`)
            resolve()
         }catch(e){
             reject()
         }
    
   })
}

function removeArticle(data){
    return  new Promise( async (resolve,reject)=>{
        try{
            if(data.id){
                const removeBookSql = `delete from fs_article where id='${data.id}'`
                await db.querySql(removeBookSql)
                resolve()
            }
        }catch(e){
            reject()
        }
    
   })
   
}




module.exports = {
    getAdminArticleList,
    updataArticle,
    addReject,
    updataReject,
    getArticle,
    removeArticle
}